package cn.uo86.bs;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.backup.FileBackupHelper;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.DownloadListener;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import cn.uo86.bs.filebrowser.FileExplorerActivity;
import cn.uo86.bs.utils.Utils;

import com.umeng.analytics.MobclickAgent;
import com.umeng.fb.UMFeedbackService;
import com.umeng.update.UmengUpdateAgent;
import com.waps.AppConnect;
import com.waps.UpdatePointsNotifier;

public class BooksearchActivity extends Activity implements OnClickListener,
		UpdatePointsNotifier, DownloadListener {
	private static final boolean DEBUG = true;
	private static final String TAG = "BooksearchActivity";

	private static WebView wv;
	private Handler myHandler = new MyHandler();
	ImageButton search_Btn;
	ImageView back_Btn;
	ImageView forward_Btn;
	ImageView home_Btn;
	ImageView refresh_Btn;
	ImageView favorite_Btn;
	EditText key_EText;

	private final String easouUrl = "http://b.easou.com/";

	private final static int COVER_HEAD = 201;
	private final static int SEARCH_NOVEL = 202;
	private final static int GET_SCORE = 203;
	public static final int BUY_SOFTWARE = 204;

	private int score = 0;
	private int requirescore = 20;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		MobclickAgent.updateOnlineConfig(this);
		MobclickAgent.onError(this);
		UmengUpdateAgent.setUpdateOnlyWifi(false);
		UmengUpdateAgent.update(this);
		AppConnect.getInstance(this);

		myHandler.sendEmptyMessageDelayed(GET_SCORE, 1000);
		// myHandler.sendEmptyMessageDelayed(BUY_SOFTWARE, 5 * 1000);

		key_EText = (EditText) this.findViewById(R.id.search_et);
		search_Btn = (ImageButton) this.findViewById(R.id.search_ImgBtn);
		back_Btn = (ImageView) this.findViewById(R.id.browser_back_btn);
		forward_Btn = (ImageView) this.findViewById(R.id.browser_forward_btn);
		home_Btn = (ImageView) this.findViewById(R.id.browser_home_btn);
		refresh_Btn = (ImageView) this.findViewById(R.id.browser_refresh_btn);
		favorite_Btn = (ImageView) this.findViewById(R.id.browser_favorite_btn);
		search_Btn.setOnClickListener(this);
		back_Btn.setOnClickListener(this);
		forward_Btn.setOnClickListener(this);
		home_Btn.setOnClickListener(this);
		refresh_Btn.setOnClickListener(this);
		favorite_Btn.setOnClickListener(this);

		wv = (WebView) this.findViewById(R.id.webView);
		wv.setWebViewClient(new MyWebViewClient());
		wv.setWebChromeClient(new MyWebChrome());
		wv.setDownloadListener(this);
		wv.getSettings().setJavaScriptEnabled(true);
		wv.getSettings().setSaveFormData(true);
		wv.getSettings().setSavePassword(false);
		wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		wv.getSettings()
				.setUserAgentString(
						"Mozilla/5.0 (Linux; U; Android 0.5; en-us) AppleWebKit/522+ (KHTML, like Gecko) Safari/419.3");
		wv.loadUrl(easouUrl);
	}

	class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			if (DEBUG)
				Utils.logi(TAG, "Message what=" + msg.what);
			switch (msg.what) {
			case COVER_HEAD:
				Utils.logd(TAG, "盖住头部动作");

				wv.scrollTo(0, msg.arg1);
				break;
			case SEARCH_NOVEL:
				String searchKey = key_EText.getText().toString().trim();
				Utils.logd(TAG, "当前关键字:" + searchKey);
				if (searchKey.length() < 2) {
					Toast.makeText(BooksearchActivity.this, "请输入搜索关键字",
							Toast.LENGTH_SHORT).show();
					return;
				}
				wv.loadUrl("javascript:document.getElementsByName(\"q\")[0].value = "
						+ "\"" + searchKey + "\";");
				wv.loadUrl("javascript:document.forms[0].submit();");
				break;
			case GET_SCORE:
				String keyword = MobclickAgent.getConfigParams(
						BooksearchActivity.this, "requirescore");
				if (keyword != null && !keyword.equals("")) {
					requirescore = Integer.valueOf(keyword);
				}
				Log.v("BooksearchActivity", "当前要求积分为:" + keyword);
				break;

			case BUY_SOFTWARE:
				boolean isBuy = readXmlBooleanByKey("isBuy");
				if (!isBuy) { // 没有购买
					Dialog dialog = new AlertDialog.Builder(
							BooksearchActivity.this)
							.setIcon(android.R.drawable.btn_star)
							.setTitle("您的积分为:" + BooksearchActivity.this.score)
							.setMessage(
									"现在只要积分满" + requirescore + "就可以使用本软件的所有功能!")
							.setPositiveButton(
									"免费获取积分",
									new android.content.DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											AppConnect
													.getInstance(
															BooksearchActivity.this)
													.showOffers(
															BooksearchActivity.this);
										}
									})
							.setNegativeButton(
									"启用",
									new android.content.DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											if (BooksearchActivity.this.score >= requirescore) {
												AppConnect
														.getInstance(
																BooksearchActivity.this)
														.spendPoints(
																requirescore,
																BooksearchActivity.this);
												writeXmlBykey("isBuy", true);
												dialog.dismiss();
											} else {
												Toast.makeText(
														getBaseContext(),
														"对不起您的积分不足,左边按钮可以免费获取哟!",
														Toast.LENGTH_LONG)
														.show();
											}
										}
									}).create();
					dialog.show();
				}
				break;
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		AppConnect.getInstance(this).finalize();
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		AppConnect.getInstance(this).getPoints(this);
		MobclickAgent.onResume(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 1, "分享");
		menu.add(0, 1, 2, "五星支持");
		menu.add(0, 2, 3, "反馈");
		menu.add(1, 3, 4, "退出");
		// getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			Utils.openAppShare(this);
			break;
		case 1:
			Utils.openAppInMarket(getPackageName(), this);
			break;
		case 2:
			UMFeedbackService.openUmengFeedbackSDK(this);
			return true;
			// break;
		case 3:
			if (!Utils.readXmlBooleanByKey(Utils.ISEXITTIP, this)) {
				Utils.exitDialog(this);
			} else {
				finish();
			}
			break;
		}
		return super.onOptionsItemSelected(item);

	}

	void sendMsg(int value, long delay) {
		Message msg = new Message();
		msg.what = COVER_HEAD;
		msg.arg1 = value;
		if (delay != 0) {
			myHandler.sendMessageDelayed(msg, delay);
		} else {
			myHandler.sendMessage(msg);

		}

	}

	class MyWebViewClient extends WebViewClient {

		@Override
		public void onPageFinished(WebView view, String url) {
			if (DEBUG)
				Utils.logi(TAG, "onPageFinished() url" + url);

			if (url.indexOf("b.easou.com/s.m") > 0) {
				sendMsg(30, 300);
				return;
			}
			if (url.equalsIgnoreCase(easouUrl)) {
				sendMsg(174, 200);
				return;
			}

			super.onPageFinished(view, url);
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			if (DEBUG)
				Utils.logi(TAG, "onPageStarted()  url" + url);

			super.onPageStarted(view, url, favicon);
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			if (DEBUG)
				Utils.logi(TAG, "shouldOverrideUrlLoading() url" + url);
			view.loadUrl(url);
			return super.shouldOverrideUrlLoading(view, url);
		}

		@Override
		public void onReceivedSslError(WebView view, SslErrorHandler handler,
				SslError error) {
			if (DEBUG)
				Utils.logi(TAG, "onReceivedSslError()");
			handler.proceed();
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			if (DEBUG)
				Utils.logi(TAG, "Enter onReceivedError(),and ErrorCode:"
						+ errorCode + "failingUrl" + failingUrl);
			super.onReceivedError(view, errorCode, description, failingUrl);
		}
	}

	class MyWebChrome extends WebChromeClient {

		@Override
		public boolean onJsAlert(WebView view, String url, String message,
				JsResult result) {
			if (DEBUG)
				Utils.logi(TAG, "onJsAlert()");
			result.confirm();
			return true;
		}

		@Override
		public boolean onJsConfirm(WebView view, String url, String message,
				JsResult result) {
			if (DEBUG)
				Utils.logi(TAG, "onJsConfirm()");
			result.confirm();
			return true;
		}

		@Override
		public boolean onJsPrompt(WebView view, String url, String message,
				String defaultValue, JsPromptResult result) {
			if (DEBUG)
				Utils.logi(TAG, "onJsPrompt() ");
			result.confirm(defaultValue);
			return true;
		}
	}

	private static Boolean isExit = false;
	private static Boolean hasTask = false;
	Timer tExit = new Timer();
	TimerTask task = new TimerTask() {

		@Override
		public void run() {
			isExit = false;
			hasTask = true;
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		System.out.println("TabHost_Index.java onKeyDown");
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if(wv.canGoBack()){
				wv.goBack();
				return true;
			}
			if (isExit == false) {
				isExit = true;
				Toast.makeText(this, "再按一次后退键退出应用程序", Toast.LENGTH_SHORT)
						.show();
				if (!hasTask) {
					tExit.schedule(task, 2000);
				}
			} else {
				finish();
				System.exit(0);
			}
		}
		return false;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.browser_back_btn:
			if (wv.canGoBack()) {
				wv.goBack();
			} else {
				Toast.makeText(getBaseContext(), "已经到头了...", Toast.LENGTH_SHORT)
						.show();
			}
			break;
		case R.id.browser_forward_btn:
			if (wv.canGoForward()) {
				wv.goForward();
			} else {
				Toast.makeText(getBaseContext(), "已经到尾了...", Toast.LENGTH_SHORT)
						.show();
			}
			break;
		case R.id.browser_home_btn:
			wv.loadUrl(easouUrl);
			break;
		case R.id.browser_refresh_btn:
			wv.reload();
			break;
		case R.id.browser_favorite_btn:
			Toast.makeText(getBaseContext(), "你可以从这里找到下载的小说哦!", Toast.LENGTH_SHORT)
					.show();
			Intent intent = new Intent(getBaseContext(),FileExplorerActivity.class);
			startActivity(intent);
			break;
		case R.id.search_ImgBtn:
			myHandler.sendEmptyMessage(SEARCH_NOVEL);
			break;
		}

	}

	public void getUpdatePoints(String paramString, int paramInt) {
		this.score = paramInt;
	}

	public void getUpdatePointsFailed(String paramString) {
		AppConnect.getInstance(this).getPoints(this);
	}

	public String readXmlStringByKey(String key) {
		SharedPreferences settings = PreferenceManager
				.getDefaultSharedPreferences(this);
		String str = settings.getString(key, "");
		return str;

	}

	public Boolean readXmlBooleanByKey(String key) {
		SharedPreferences settings = PreferenceManager
				.getDefaultSharedPreferences(this);
		Boolean isTrue = settings.getBoolean(key, false);
		return isTrue;

	}

	public void writeXmlBykey(String key, String value) {
		Editor e = PreferenceManager.getDefaultSharedPreferences(this).edit();
		e.putString(key, value);
		e.commit();
	}

	public void writeXmlBykey(String key, Boolean value) {
		Editor e = PreferenceManager.getDefaultSharedPreferences(this).edit();
		e.putBoolean(key, value);
		e.commit();
	}

	/**
	 * webView 有文件下载时 CALL
	 * 
	 */
	@Override
	public void onDownloadStart(String url, String userAgent,
			String contentDisposition, String mimetype, long contentLength) {

		if (DEBUG)
			Utils.logi(TAG, "onDownloadStart() url=" + url + " userAgent="
					+ userAgent + " contentDisposition=" + contentDisposition
					+ "  mimetype=" + mimetype + "  contentLength="
					+ contentLength);
		
		Intent intent = new Intent(getBaseContext(),DownFileActivity.class);
		intent.putExtra("URL", url);
		intent.putExtra("TOTALSIZE", contentLength);
		startActivity(intent);
	}

}